package com.example.myapplication

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.ByteArrayOutputStream

class SecondActivity : AppCompatActivity() {
    private lateinit var imageView: ImageView
    private lateinit var mName: EditText
    private lateinit var mXuehao: EditText
    private lateinit var mPhone: EditText
    private lateinit var mAddress: EditText
    private lateinit var radioGroup: RadioGroup
    private lateinit var checkboxTravel: CheckBox
    private lateinit var checkboxReading: CheckBox
    private lateinit var checkboxShopping: CheckBox
    private lateinit var checkboxCoding: CheckBox

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_second)

        initViews()
        setupListeners()
    }

    // 初始化视图
    private fun initViews() {
        imageView = findViewById(R.id.imageView2)
        mName = findViewById(R.id.m_name)
        mXuehao = findViewById(R.id.m_xuehao)
        mPhone = findViewById(R.id.m_phone)
        mAddress = findViewById(R.id.m_address)

        radioGroup = findViewById(R.id.radioGroupGender)
        checkboxTravel = findViewById(R.id.checkboxTravel)
        checkboxReading = findViewById(R.id.checkboxReading)
        checkboxShopping = findViewById(R.id.checkboxShopping)
        checkboxCoding = findViewById(R.id.checkboxCodeing)
    }

    // 设置按钮监听
    private fun setupListeners() {
        findViewById<Button>(R.id.buttonTakePhoto).setOnClickListener {
            takePhoto()
        }

        findViewById<Button>(R.id.backbutton).setOnClickListener {
            finish() // 直接返回，不传数据
        }

        findViewById<Button>(R.id.submitButton).setOnClickListener {
            submitData()
        }
    }

    // 拍照
    private fun takePhoto() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        cameraActivityResultLauncher.launch(intent)
    }

    private val cameraActivityResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                val imageBitmap = data?.extras?.get("data") as? Bitmap
                imageBitmap?.let {
                    imageView.setImageBitmap(it)
                }
            }
        }
    // 提交数据
    private fun submitData() {
        val gender = getSelectedGender()
        val hobbies = getSelectedHobbies()

        val returnIntent = Intent().apply {
            putExtra("name", mName.text.toString())
            putExtra("ID", mXuehao.text.toString())
            putExtra("phone", mPhone.text.toString())
            putExtra("address", mAddress.text.toString())
            putExtra("gender", gender)
            putExtra("hobbies", hobbies.joinToString(", "))
            putExtra("image", getImageByteArray())
        }

        setResult(RESULT_OK, returnIntent)
        finish()
    }
    private fun getSelectedGender(): String {
        val selectedId = radioGroup.checkedRadioButtonId
        return if (selectedId != -1) findViewById<RadioButton>(selectedId).text.toString()
        else "未选择"
    }
    private fun getSelectedHobbies(): List<String> {
        val list = mutableListOf<String>()
        if (checkboxTravel.isChecked) list.add("旅游")
        if (checkboxReading.isChecked) list.add("阅读")
        if (checkboxShopping.isChecked) list.add("游戏")
        if (checkboxCoding.isChecked) list.add("购物")
        return list
    }
    private fun getImageByteArray(): ByteArray {
        val drawable = imageView.drawable as? BitmapDrawable
        val bitmap = drawable?.bitmap ?: Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
        return ByteArrayOutputStream().apply {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, this)
        }.toByteArray()
    }
}
